import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Welfare from 'src/entities/welfare.entity';
import { Repository } from 'typeorm';
import { CreateWelfareDto, FindWelfareDto, UpdateWelfareDto } from './welfare.dto';
import { isEmpty } from 'lodash';
import { ApiException } from 'src/core/exceptions/api.exception';

@Injectable()
export class WelfareService {
  constructor(@InjectRepository(Welfare) private welfareRepository: Repository<Welfare>) {}

  // 查询福利列表
  async find(query: FindWelfareDto) {
    const { page, size, name, enableStatus } = query;

    const queryBuilder = this.welfareRepository
      .createQueryBuilder('welfare')
      .orderBy('welfare.order', 'ASC')
      .skip(size * (page - 1))
      .take(size);

    if (name !== undefined) {
      queryBuilder.andWhere('welfare.name LIKE :name', { name: `%${name}%` });
    }

    if (enableStatus !== undefined) {
      queryBuilder.andWhere('welfare.enable_status = :enableStatus', { enableStatus });
    }

    const [list, count] = await queryBuilder.getManyAndCount();
    return { list, count };
  }

  // 新增福利
  async create(createWelfareDto: CreateWelfareDto) {
    const welfare = await this.welfareRepository.findOne({
      where: { name: createWelfareDto.name },
    });
    if (!isEmpty(welfare)) {
      throw new ApiException(13001);
    }

    const newWelfare = this.welfareRepository.create(createWelfareDto);
    await this.welfareRepository.save(newWelfare);
  }

  // 更新福利
  async update(updateWelfareDto: UpdateWelfareDto) {
    const welfare = await this.welfareRepository.findOne({ where: { id: updateWelfareDto.id } });
    if (isEmpty(welfare)) {
      throw new ApiException(13002);
    }

    const updateWelfare = this.welfareRepository.merge(welfare, updateWelfareDto);
    await this.welfareRepository.save(updateWelfare);
  }
}
